package service

import (
	"context"
	"encoding/json"
	"time"

	"github.com/gogf/gf/v2/os/gcache"
)

var Cache = cacheService{
	cache: gcache.New(),
}

type cacheService struct {
	cache *gcache.Cache
}

func (s *cacheService) Set(key string, value interface{}, duration time.Duration) error {
	return s.cache.Set(context.Background(), key, value, duration)
}

func (s *cacheService) Get(key string, out interface{}) error {
	value, err := s.cache.Get(context.Background(), key)
	if err != nil {
		return err
	}
	if value == nil {
		return nil
	}

	bytes, err := json.Marshal(value)
	if err != nil {
		return err
	}

	return json.Unmarshal(bytes, out)
}

func (s *cacheService) Remove(key string) error {
	_, err := s.cache.Remove(context.Background(), key)
	return err
}
